package com.example.servlet;

import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(name = "QuizAdminServlet", urlPatterns = "/quiz-admin")
public class QuizAdminServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String deleteId = req.getParameter("delete");
        if (deleteId != null) {
            try {
                int delId = Integer.parseInt(deleteId);
                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement ps = conn.prepareStatement("DELETE FROM quiz_questions WHERE id=?")) {
                    ps.setInt(1, delId);
                    ps.executeUpdate();
                    resp.sendRedirect("quiz-admin");
                    return;
                }
            } catch (NumberFormatException e) {
                // 非法id，忽略删除
                resp.sendRedirect("quiz-admin");
                return;
            } catch (Exception e) {
                e.printStackTrace();
                resp.getWriter().write("<h3>删除失败</h3>");
                return;
            }
        }
        // 查询所有题目
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM quiz_questions")) {
            StringBuilder sb = new StringBuilder();
            sb.append("<table border='1'><tr><th>ID</th><th>题目</th><th>A</th><th>B</th><th>C</th><th>D</th><th>答案</th><th>操作</th></tr>");
            while (rs.next()) {
                sb.append("<tr>")
                  .append("<td>").append(rs.getInt("id")).append("</td>")
                  .append("<td>").append(rs.getString("question")).append("</td>")
                  .append("<td>").append(rs.getString("option_a")).append("</td>")
                  .append("<td>").append(rs.getString("option_b")).append("</td>")
                  .append("<td>").append(rs.getString("option_c")).append("</td>")
                  .append("<td>").append(rs.getString("option_d")).append("</td>")
                  .append("<td>").append(rs.getString("answer")).append("</td>")
                  .append("<td><a href='quiz-admin?delete=").append(rs.getInt("id")).append("'>删除</a></td>")
                  .append("</tr>");
            }
            sb.append("</table>");
            // 添加题目表单
            sb.append("<form method='post'>"
                    + "题目：<input name='question' required> "
                    + "A：<input name='option_a' required> "
                    + "B：<input name='option_b' required> "
                    + "C：<input name='option_c' required> "
                    + "D：<input name='option_d' required> "
                    + "答案：<input name='answer' required maxlength='1' size='1'> "
                    + "解析：<input name='explanation'> "
                    + "<input type='submit' value='添加题目'>"
                    + "</form>");
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().write(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("<h3>查询失败</h3>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 添加题目
        String question = req.getParameter("question");
        String option_a = req.getParameter("option_a");
        String option_b = req.getParameter("option_b");
        String option_c = req.getParameter("option_c");
        String option_d = req.getParameter("option_d");
        String answer = req.getParameter("answer");
        String explanation = req.getParameter("explanation");
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                     "INSERT INTO quiz_questions(question, option_a, option_b, option_c, option_d, answer, explanation) VALUES (?, ?, ?, ?, ?, ?, ?)");) {
            ps.setString(1, question);
            ps.setString(2, option_a);
            ps.setString(3, option_b);
            ps.setString(4, option_c);
            ps.setString(5, option_d);
            ps.setString(6, answer);
            ps.setString(7, explanation);
            ps.executeUpdate();
            resp.sendRedirect("quiz-admin");
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("<h3>添加失败</h3>");
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 预留：可实现AJAX删除
    }
} 